package com.bridgetree.jubaocrm.ui.project;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.ui.widget.XListView;
import com.bridgetree.jubaocrm.ui.widget.XListView.IXListViewListener;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.OfferInterface;
import com.bridgetree.jubaocrm.util.Projects;
import com.bridgetree.jubaocrm.util.Quotes;
/**
 *报价
 */
public class XMChildOfferActivity extends Activity {
	private final String TAG ="XMChildOfferActivity";
	private PullToRefreshListView xm_of_lv = null;
	private ListView actualListView1 = null;
	private XMChildOfferAdapter mXMChildOfferAdapter = null;
	private Projects mProjects;
	private Context mContext;
	private String user_id =""; 
	private String token ="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xm_offer);
		mContext=this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");
		}

		findViewById(R.id.xm_of_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		xm_of_lv=(PullToRefreshListView)findViewById(R.id.xm_of_lv);
		xm_of_lv.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if(mXMChildOfferAdapter!=null)
					mXMChildOfferAdapter.notifyDataSetChanged();
				if(xm_of_lv!=null)
					xm_of_lv.onRefreshComplete();
			}
		});

		xm_of_lv.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				//				if(firstVisibleItem+visibleItemCount == totalItemCount){
				//					scrollTopBottom=1;
				//				}else if(firstVisibleItem == 0){
				//					scrollTopBottom=0;
				//				}
			}
		});
		actualListView1 = xm_of_lv.getRefreshableView();
		if(mProjects!=null){
			getOffer();
		}

	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	private void getOffer() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			String URL = Network.API_DOMAIN+"/quotes?" +
			"pid="+mProjects.getProject_id() +"&user_id="+user_id+
			"&token="+token+"&validation="+CRMUserBaseInfo.kValication;

			final ProgressDialog progressDialog = ProgressDialog.show(this, "网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {  
						@Override
						public void onResponse(JSONObject response) {
							//							System.out.println("报价 response="+response);  
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								OfferInterface mOfferInterface = new OfferInterface();
								if (!response.isNull("quotes")) {
									org.json.JSONArray jsonArr;
									if (!response.isNull("quotes")) {
										List<Quotes> mQuotes = new ArrayList<Quotes>();
										jsonArr = response.getJSONArray("quotes");
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr.length(); i++) {
												Quotes mQuote = new Quotes();
												JSONObject jsonObj2 = jsonArr.getJSONObject(i);
												if (!jsonObj2.isNull("quote_date")) {
													String quote_date = jsonObj2.getString("quote_date");
													mQuote.setQuote_date(quote_date);
												}
												if (!jsonObj2.isNull("discount")) {
													mQuote.setDiscount(jsonObj2.getString("discount"));
												}
												if (!jsonObj2.isNull("price")) {
													mQuote.setPrice(jsonObj2.getString("price"));
												}
												if (!jsonObj2.isNull("one_price")) {
													String one_price = jsonObj2.getString("one_price");	
													mQuote.setOne_price(one_price);
												}
												if (!jsonObj2.isNull("quote_people")) {
													String quote_people = jsonObj2.getString("quote_people");	
													mQuote.setQuote_people(quote_people);
												}
												mQuotes.add(mQuote);
											}
										}
										mOfferInterface.setQuotes(mQuotes);
									}
								}
								if (!response.isNull("is_member_of_project")) {
									boolean is_member_of_project =Boolean.valueOf(response.get("is_member_of_project").toString());
									mOfferInterface.setIs_member_of_project(is_member_of_project);
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														mLoginError.setDesc(desc);
														openDailog("失败提示", desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
											mOfferInterface.setErrors(mLoginError);
										}
									}
								}
								//								map = new HashMap<String,Object>();
								//								map.put("name", "刘德华");
								//								map.put("time", "2014-04-22");
								//								map.put("allprice", "555558");
								//								map.put("aprice", "1524");
								//								map.put("zhikou", "245");
								//								proInfoListData.add(map);
								mXMChildOfferAdapter = new XMChildOfferAdapter(XMChildOfferActivity.this,mOfferInterface.getQuotes());
								actualListView1.setAdapter(mXMChildOfferAdapter);
								if (xm_of_lv != null) {
									xm_of_lv.onRefreshComplete();
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					},
					new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) { 
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");  
						}  
					});  
			requestQueue.add(jsonObjectRequest); 
		}

	}

}

class XMChildOfferAdapter extends BaseAdapter {
	private List<Quotes> DrugstoreDataList = null;
	private LayoutInflater listContainer; // 视图容器

	public final class ListItemView { // 自定义控件集合
		public TextView xm_of_item_tv1; 
		public TextView xm_of_item_tv2; 
	}

	public XMChildOfferAdapter(Context mContext, List<Quotes> data) {
		this.DrugstoreDataList = data;
		listContainer = (LayoutInflater) mContext
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		if (DrugstoreDataList != null) {
			return DrugstoreDataList.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return DrugstoreDataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ListItemView listItemView = null;
		if (convertView == null) {
			listItemView = new ListItemView();
			// 获取list_item布局文件的视图
			convertView = listContainer.inflate(R.layout.xm_offer_item, null);
			// 获取控件对象
			listItemView.xm_of_item_tv1 = (TextView) convertView.findViewById(R.id.xm_of_item_tv1);
			listItemView.xm_of_item_tv2 = (TextView) convertView.findViewById(R.id.xm_of_item_tv2);
			// 设置控件集到convertView
			convertView.setTag(listItemView);
		} else {
			listItemView = (ListItemView) convertView.getTag();
		}
		String line1 = (String) DrugstoreDataList.get(position).getQuote_people()+
		"于"+(String) DrugstoreDataList.get(position).getQuote_date()+
		"报价"+DrugstoreDataList.get(position).getPrice()+"元";
		listItemView.xm_of_item_tv1.setText(line1);
		String line2 ="单价："+ (String) DrugstoreDataList.get(position).getOne_price()+
		"，折扣："+DrugstoreDataList.get(position).getDiscount();
		listItemView.xm_of_item_tv2.setText(line2);
		return convertView;
	}

}
